package com.education.cms.filter;

import com.education.cms.utils.RedisUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter(filterName = "AdminFilter")
public class AdminFilter implements Filter {
    private String ignoreURL;
    private RedisUtils redisUtils;


    public AdminFilter(RedisUtils redisUtils){
        this.redisUtils=redisUtils;
    }
    public void init(FilterConfig config) throws ServletException {
        ignoreURL = config.getInitParameter("ignoreURL");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;

        if (request.getServletPath().equals(ignoreURL)){
            chain.doFilter(req,resp);
        }else {
            String ticket = (String) request.getAttribute("ticket");
            String[] content=redisUtils.get(ticket).split("-");
            if (content[1].equals("8")){
                chain.doFilter(req,resp);
            }else {
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("您不是管理员，无权操作此页面！如有疑问请联系管理员~");
            }
        }
    }


    public void destroy() {
    }

}
